package com.grj.service.article.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.grj.model.article.entity.Article;
import com.grj.model.article.entity.Liked;
import com.grj.service.article.config.MinioProperties;
import com.grj.service.article.service.ArticleService;
import com.grj.service.article.service.LikedService;
import common.filter.Result;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * @author 14505
 */
@RestController
@RequestMapping("/article")
@RequiredArgsConstructor
public class ArticleController {
    private final ArticleService articleService;

    private final Configuration configuration;

    private final MinioClient minioClient;

    private final MinioProperties minioProperties;

    private final LikedService likedService;

    private final StringRedisTemplate stringRedisTemplate;


    @GetMapping("/list")
    public Result<Object> list() {
        return Result.success(articleService.list());
    }

    @GetMapping("/{id}")
    public String get(@PathVariable Integer id, HttpServletResponse response) throws IOException {
        Article article = articleService.getById(id);
        CompletableFuture<Article> articleCompletableFuture = CompletableFuture.supplyAsync(() -> articleService.getById(id));
        LambdaQueryWrapper<Liked> eq = new LambdaQueryWrapper<Liked>().eq(Liked::getAid, id);
        eq.eq(Liked::getStatus, 1);
        List<Liked> list = likedService.list(eq);
        CompletableFuture<List<Liked>> listCompletableFuture = CompletableFuture.supplyAsync(() -> likedService.list(eq));
        response.setContentType("text/html; charset=utf-8");
        return "<!doctype html>\n" +
                "<html lang=\"zh\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <meta name=\"viewport\"\n" +
                "          content=\"width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0\">\n" +
                "    <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n" +
                "    <title>Document</title>\n" +
                "<style>\n" +
                "   html,body{\n" +
                "        margin: 0;\n" +
                "        padding: 0;\n" +
                "   }\n" +
                "   iframe {\n" +
                "        width: 100%;\n" +
                "        margin: 0;\n" +
                "        border: 0;\n" +
                "        outline: 0;\n" +
                "        background: lightskyblue;\n" +
                "    }\n" +
                "</style>\n" +
                "</head>\n" +
                "<body>\n" +
                "<h1>" + article.getTitle() + "</h1>\n" +
                "<a href='http://localhost:8080/nk-service-article/article/like/"+ article.getId() + "'>点赞</a>\n" +
                "<p>" + article.getUid() + "</p>\n" +
                "<iframe src="+article.getDetailurl()+"></iframe>\n" +
                "\n" +
                "<p>" + list.size() + "</p>\n" +
                "</body>\n" +
                "</html>";
    }

    @PostMapping
    public Result<Object> add(@RequestBody Article article, HttpServletRequest request) throws Exception {

        article.setId(null);

        // 设置字符集
        configuration.setDefaultEncoding("utf-8");
        // 加载模板
        Template template = configuration.getTemplate("article.ftl");
        // 数据模型
        Map<String,Object> map = new HashMap<>();
        map.put("article", article);
        // 静态化
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
        // 打印静态化内容
        InputStream inputStream = IOUtils.toInputStream(content);
        // 输出文件
//        FileOutputStream fileOutputStream = new FileOutputStream("article.html");
//        int copy = IOUtils.copy(inputStream, fileOutputStream);


        minioClient.putObject(
                PutObjectArgs.builder().bucket(minioProperties.getBucketName()).object(article.getTitle()).stream(
                        inputStream, -1, 100000000)
                        .contentType("text/html")
                        .build());

        article.setDetailurl(minioClient.getObjectUrl(minioProperties.getBucketName(), article.getTitle()));
        articleService.save(article);
        return Result.success(article);
    }


    @GetMapping("like/{aid}")
    public String get(@PathVariable Integer aid) {
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps("article::like::"+aid);
        long round = Math.round(Math.random() * 10);
        String uid = String.valueOf(round);
        String status = String.valueOf(Math.round(Math.random() * 10)%2);
        ops.put(uid, status);
        return Objects.requireNonNull(ops.entries()).toString();
    }

    @PostMapping("likes")
    public void likes(@RequestBody String s) {
        String[] split = s.split("///");
        List<String> keys = JSONUtil.toList(split[0], String.class);
        List<Liked> likes = JSONUtil.toList(split[1], Liked.class);
        Map<String, Object> map = new HashMap<>();
        likes.forEach(i->{
            map.put("uid",i.getUid());
            map.put("aid",i.getAid());
        });
        likedService.removeByMap(map);
        likedService.saveOrUpdateBatch(likes);
        stringRedisTemplate.delete(keys);
    }
}
